package streaming.log

import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent

object LogStatisticsApp {

  def main(args: Array[String]): Unit = {
    if (args.length != 3) {
      System.err.println("Usage: LogStatisticsApp <bootstrapServers> <groupId> <topics>")
      System.exit(1)
    }

    val Array(bootstrapServers, groupId, topics) = args

    val sc = new SparkConf().setMaster("local[*]").setAppName("LogStatisticsApp")
    val ssc = new StreamingContext(sc, Seconds(10))

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> bootstrapServers,
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> groupId,
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    val messages = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics.split(",").toArray, kafkaParams)
    )

    val result = messages.map(m => {
      // 111.166.77.83	2018-12-18 23:11:38	"GET class/122.html HTTP/1.1"	-	404
      val infos = m.value().split("\t")
      val url = infos(2).split(" ")(1)

      var courseId = 0

      // 课程编号
      if (url.startsWith("/class")) {
        val courseIdHtml = url.split("/")(2)
        courseId = courseIdHtml.substring(0, courseIdHtml.lastIndexOf(".")).toInt
      }

      ClickLog(infos(0), DateUtils.parseToMinute(infos(1)), courseId, infos(3), infos(4).toInt)

    }).filter(_.courseId > 0)

    result.print()

    ssc.start()
    ssc.awaitTermination()
  }
}
